package com.yonyou.ucf.mdf.app.isvdxq.yonyisv.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.common.SuiteConfig;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.SuiteauthEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.MyTokenService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.SuiteService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.SuiteauthService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyExtend;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.TenantUserBean;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.service.OpenApiRequestService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 免登示例
 */
@RequestMapping(value = {DxqConfig.pre_apiUrl+"",DxqConfig.pre_pcUrl+""})
@RestController
public class LoginFreeController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFreeController.class);

    @Autowired
    private SuiteConfig suiteConfig;

    @Autowired
    private OpenApiRequestService requestService;

    @Autowired
    private SuiteService suiteService;
    //私有表存储
    @Autowired
    private SuiteauthService suiteauthService;
    @Autowired
    private MyTokenService myTokenService;

    @Autowired
    BaseService baseService;

    /**
     * 默认应用免登 获取用户信息
     * @param code
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws IOException
     */
    @GetMapping("/login")
    public LoginFreeResponse loginFree(@RequestParam String code) throws NoSuchAlgorithmException,
            InvalidKeyException, IOException {
        LOGGER.info("新的免登请求, code: {}", code);
        Suite suite = suiteService.getSuite(suiteConfig.getSuiteKey());
        if (suite == null || suite.getSuiteTicket() == null) {
            throw new RuntimeException("套件尚未初始化，或尚未推送 ticket！");
        }

        LoginFreeResponse response = requestService.requestForLogin(suite.getSuiteKey(), code, suite.getSuiteTicket()
                , suite.getSuiteSecret());
        LOGGER.info("成功获得用户信息：{}", response);
        return response;
    }

    /**
     * 免登获取用户信息
     * @param code
     * @param suiteKey
     * @param suiteSecret
     * @param request
     * @return
     */
    @GetMapping("/login/V1")
    public String loginFreeV1(@RequestParam String code, @RequestParam String suiteKey,
                              @RequestParam String suiteSecret, HttpServletRequest request) {
        LOGGER.info("新的免登请求, code: {}", code);
        try {
            LoginFreeResponse response = requestService.requestForLoginV2(suiteKey, code, suiteSecret);
            LOGGER.info("成功获得用户信息：{}", response);
            //获取套件授权
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            if (!StringUtils.isEmpty(tenantId)) {
                SuiteAuth suiteAuth = suiteService.getSuiteAuth(suiteKey, tenantId);
                suiteKey = suiteAuth.getSuiteKey();
            }
            LOGGER.info("[login/V2]" + suiteKey + "|" + suiteSecret + "|" + code);
            return JSONObject.toJSONString(response);
        } catch (Exception ex) {
            LOGGER.error("[新的免登请求]" + ex.getMessage());
        }
        return code;
    }

    /**
     * 授权后才能免密登录 直接返回code
     * @param code
     * @param request
     * @param response
     */
    @GetMapping("/login/V2")
    public String loginFreeV2(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            LOGGER.info("新的免登请求getlogincode, code: {}", code);
            //获取套件授权
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            String yhtAccessToken = RequestTool.getHeaderAndParameter(request, "yht_access_token");
            String suiteTicket = request.getParameter("suiteTicket");
        } catch (Exception ex) {
            LOGGER.error("[新的免登请求getlogincode]" + ex.getMessage());
        }
        return code;
    }

    @GetMapping("/login/V3")
    public void loginFreeV3(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code); //换取租户列表
        try {
            LOGGER.info("新的免登请求getlogincode, code: {}", code);
            //获取套件授权
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            String yhtAccessToken = RequestTool.getHeaderAndParameter(request, "yht_access_token");
            String suiteTicket = request.getParameter("suiteTicket");
            if (!StringUtils.isEmpty(tenantId)) {
                SuiteAuth suiteAuth = suiteService.getSuiteAuth(DxqConfig.suiteKey, tenantId);
                LOGGER.info("成功获得用户信息：{}", suiteAuth);
            }
            // 获取 cookies
            if (!StringUtils.isEmpty(yhtAccessToken)) RequestTool.writeCookieToDevice(request, response, "yht_access_token", yhtAccessToken);
            if (request.getCookies() != null){
                Cookie[] cookies = request.getCookies();
                for(Cookie cookie: cookies){
                    RequestTool.writeCookieToDevice(request, response, cookie.getName(), cookie.getValue());
                }
            }
            // 默认环境网关
            String apiUrl = myTokenService.getProperty("runtime.server.url", null);
            String domainKey = myTokenService.getProperty("bpmrest.appsource", null);
            String env = myTokenService.getProperty("spring.profiles.active", null);
            String gatewayurl = myTokenService.getProperty("openapi.apiprifx", null);
            hashMap.put("env", env);
            hashMap.put("domainKey", domainKey);
            hashMap.put("baseUrl", apiUrl);
            hashMap.put("apiUrl", String.format("%s%s", apiUrl, DxqConfig.pre_apiUrl));
            hashMap.put("gatewayurl", gatewayurl);

            // 获取租户列表
            Map<String, String> params = new HashMap<>();
            params.put("code", code); //换取租户列表
            String requestUrl = DxqConfig.openApiUrlGateway + ApiYon.getBaseInfoByCode;
            String responseString = RequestTool.doGet(requestUrl, params);
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            if (jsonObject.getString("code").equals("00000")) {
                JSONObject data = jsonObject.getJSONObject("data");
                TenantUserBean tenantUserBean = MyTool.convertBean2Bean(data, TenantUserBean.class);
                List<String> tenantIds = tenantUserBean.getTenantList().stream().map(it -> it.getTenantId()).collect(Collectors.toList());
                List<SuiteauthEntity> suiteauthEntities = suiteauthService.SelectByTenantIds(tenantIds);
                tenantUserBean.getTenantList().forEach(item->{
                    SuiteauthEntity suiteauthEntity = suiteauthEntities.stream().filter(it -> it.getTenant_id().equals(item.getTenantId())).findFirst().orElse(null);
                    if (suiteauthEntity!=null) item.setGatewayUrl(suiteauthEntity.getGatewayUrl());
                });
                hashMap.put("data", tenantUserBean);
            }
        } catch (Exception ex) {
            LOGGER.error("[新的免登请求getlogincode]" + ex.getMessage());
        }
//        RequestTool.renderJson(response, JSONObject.toJSONString(hashMap));
        RequestTool.renderHtml(response, code);
    }
}
